'use strict';

const Controller = require('egg').Controller;
const JWT = require('jsonwebtoken')
class HomeController extends Controller {
  // 登录
  async login() {
    const {
      ctx
    } = this;
    let {
      username,password
    } = ctx.request.body;
    const post = await this.app.mysql.get('list', {
      username: username
    });
    if (post) {
      const passif = await this.app.mysql.get('list', {
        username: username,
        password: password
      });
      if (passif) {
        ctx.body = {
          code: 200,
          mes: '登录成功',
          token: JWT.sign(passif.id, 'mxk')
        }
      } else {
        ctx.body = {
          code: 401,
          mes: '密码错误'
        }
      }
    } else {
      ctx.body = {
        code: 404,
        mes: '用户名不存在'
      }
    }
  }
  // 注册
  async zhu() {
    const {
      ctx
    } = this;
    let {
     ruleForm,data1
    } = ctx.request.body;
    let {username,password} = ruleForm
   

    const post = await this.app.mysql.get('list', { username: username });
    if (post) {
      ctx.body = {
        code: 502,
        mes: '用户名已存在'
      }
    } else {
      const result = await this.app.mysql.insert('list', {  username: username,type:'', password: password,data:data1._value});
      if(result){
        ctx.body = {
          code:200,
          mes:'注册成功!!!'
        }
      }
    }
  }
  // 获取用户信息
  async user () {
    const {
      ctx
    } = this;
    let {
     token
    } = ctx.request.body;
    const id = JWT.verify(token,'mxk')
    const data = await this.app.mysql.get('list', { id:id });
    if(data){
      ctx.body={
        code:200,
        data:data
      }
    }
  }
}

module.exports = HomeController;
